package com.xhwl.centiotdata.suppliersystem.huawei.sheshiyun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.service.sysconfig.ISsyConfigService;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.config.SsyConfig;
import com.xhwl.common.utils.HttpUtils;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 19:03 2021/12/15
 */
@Component
public class AuthApiImpl implements IAuthApi{

    @Autowired
    private ISsyConfigService ssyConfigService;

    private static final Logger log = LoggerFactory.getLogger(AuthApiImpl.class);

    private static final Map<Integer, String> TOKEN_MAP = new HashMap<>();

    @Override
    public ResultJson login(Integer projectId){

        SsyConfig config = ssyConfigService.findByProjectId(projectId);

        if(null == config){
            log.warn("项目 {} 获取配置信息失败", projectId);
            return ResultJson.fail("配置参数错误");
        }

        if(StringUtils.isEmpty(config.getLoginAccount())){
            return ResultJson.fail("配置参数错误，loginAccount");
        }
        if(StringUtils.isEmpty(config.getCredential())){
            return ResultJson.fail("配置参数错误, credential");
        }
        if(StringUtils.isEmpty(config.getTenantId())){
            return ResultJson.fail("配置参数错误，tenant-id");
        }
        if(StringUtils.isEmpty(config.getClientId())){
            return ResultJson.fail("配置参数错误, client_id");
        }
        if(StringUtils.isEmpty(config.getClientSecret())){
            return ResultJson.fail("配置参数错误, client_secret");
        }
        if(StringUtils.isEmpty(config.getHost())){
            return ResultJson.fail("配置参数错误, host");
        }
        log.info("获取到的配置参数 {}", JSONObject.toJSONString(config));
        if(StringUtils.isNotEmpty(TOKEN_MAP.get(projectId))){
            UserLoginResult verify = verify(TOKEN_MAP.get(projectId), config);
            if(null != verify){
                return ResultJson.success(verify);
            }
        }

        String accessToken = anonymousLogin(config);
        if(StringUtils.isEmpty(accessToken)){
            return ResultJson.fail("匿名授权失败");
        }
        // 用户登录
        UserLoginResult userLoginResult = userLogin(accessToken, config);
        TOKEN_MAP.put(projectId, userLoginResult.getLoginAccessToken());
        return ResultJson.success(userLoginResult);
    }


    /**
     * 用户登录授权
     * @param accessToken
     * @param config
     * @return
     */
    private UserLoginResult userLogin(String accessToken, SsyConfig config){
        final String loginUrl = "/service/SmartCampus__SystemManagement/1.0.0/system/login";
//        String host = "https://qa1-dev1.besclouds.com";
//        String host = "https://appcuberun.cn-north-4.huaweicloud.com";
        Map<String, String> header1 = new HashMap<>();
        header1.put("access-token", accessToken);
        Map<String, String> body1 = new HashedMap();
        header1.put("Content-Type", "application/json");
        body1.put("loginAccount", config.getLoginAccount());
        body1.put("credential", config.getCredential());
        body1.put("captchaCredential", "");
        body1.put("isAgreePrivacyStatement", "true");
        HttpResponse httpResponse1 = null;
        try {
            httpResponse1 = HttpUtils.doPost(config.getHost(), loginUrl, header1,
                    body1, JSONObject.toJSONString(body1));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Header[] headers = httpResponse1.getHeaders("Set-Cookie");

        String loginAccessToken = "";
        for (Header header2 : headers) {
            log.info("cookie header : {}", header2.getValue());
            if(header2.getValue().contains("access-token")){
                String[] split = header2.getValue().split(";");
                String s = split[0];
                String substring = s.substring(13, s.length());
                loginAccessToken = substring;
                break;
            }
        }
        if(StringUtils.isEmpty(loginAccessToken)){
            log.error("获取token失败");
        }
        String identityId = null;
        if(200 == httpResponse1.getStatusLine().getStatusCode()){
            String str = "";
            try {
                str = EntityUtils.toString(httpResponse1.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            List<JSONObject> result = (List<JSONObject>) JSON.parseObject(str).get("result");
            JSONObject jsonObject1 = (JSONObject) result.get(0).get("loginResult");
            identityId = (String) jsonObject1.get("IdentityID");
            log.info("用户登录结果 {}, accessToken {}", JSON.parseObject(str), loginAccessToken);
            return new UserLoginResult(identityId, loginAccessToken);
        }else{
            try {
                log.error("第三方接口获取异常 code {},  {}", httpResponse1.getStatusLine().getStatusCode(), EntityUtils.toString(httpResponse1.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            throw new RuntimeException("第三方接口获取异常");
        }
    }

    /**
     * 匿名授权
     * @param config
     * @return
     */
    private String anonymousLogin(SsyConfig config){
        Map<String, String> header = new HashMap<>();

//        String host = "https://qa1-dev1.besclouds.com";
//        String host = "https://appcuberun.cn-north-4.huaweicloud.com";
        header.put("Content-Type", "application/x-www-form-urlencoded");
        HttpResponse httpResponse = null;
        Map<String, String> body = new HashMap<>();
        body.put("grant_type", "client_credentials");
        body.put("client_id", config.getClientId());
        body.put("client_secret", config.getClientSecret());
        try {
            httpResponse = HttpUtils.doPost(config.getHost(), "/baas/auth/v1.0/oauth2/token", header,
                    body, JSONObject.toJSONString(body));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        if(200 == httpResponse.getStatusLine().getStatusCode()){
            String str = "";
            try {
                str = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            jsonObject = JSON.parseObject(str);
        }else{
            try {
                log.error("第三方接口获取异常 {}", EntityUtils.toString(httpResponse.getEntity()));
                for (Header allHeader : httpResponse.getAllHeaders()) {
                    log.info(allHeader.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            return null;
        }
        return (String) jsonObject.get("access_token");
    }

    private UserLoginResult verify(String token, SsyConfig config){
        if(StringUtils.isEmpty(token)){
            return null;
        }
//        String host = "https://qa1-dev1.besclouds.com";
//        String host = "https://appcuberun.cn-north-4.huaweicloud.com";
        final String url = "/service/SmartCampus__UnifiedPortal/1.0.0/verifyLogin";
        HttpResponse httpResponse = null;
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        header.put("access-token", token);
        try {
            httpResponse = HttpUtils.doPost(config.getHost(), url, header,
                    null, "{}");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject jsonObject = null;
        if(200 == httpResponse.getStatusLine().getStatusCode()){
            String str = "";
            try {
                str = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            jsonObject = JSON.parseObject(str);
            if("0".equals(jsonObject.get("resCode"))){
                List<JSONObject> result1 = (List) jsonObject.get("result");
                JSONObject o = result1.get(0);
                UserLoginResult result = new UserLoginResult(o.get("identityId").toString(), token);
                return result;
            }
            return null;
        }else{
            try {
                log.error("第三方接口获取异常 {}", EntityUtils.toString(httpResponse.getEntity()));
                for (Header allHeader : httpResponse.getAllHeaders()) {
                    log.info(allHeader.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    @Deprecated
    private JSONObject getAuthCode(UserLoginResult userLoginResult, SsyConfig config){
        JSONObject jsonObject = null;
        final String authUrl = "/service/SmartCampus__UnifiedPortal/1.0.0/oauth2/getAuthCode";
//        String redirectUrl = "https://appcuberun.cn-north-4.huaweicloud.com/magno/render/SmartCampus__SystemManagement_0000000000jZP4LkS8CO/Login?client_type=hwstaff_ngba02_IntegrationAuth&code="+loginAccessToken+"&tenant-id=0000000000jZP4LkS8CO";
        String redirectUrl = "https://appcuberun.cn-north-4.huaweicloud.com/magno/render/SmartCampus__SystemManagement_0000000000jZP4LkS8CO/Login?client_type=hwstaff_ngba02_IntegrationAuth";
        Map<String, String> header2 = new HashMap<>();
        header2.put("Content-Type", "application/json");
        header2.put("access-token", userLoginResult.getLoginAccessToken());
        Map<String, String> body2 = new HashedMap();
        body2.put("redirectUri", redirectUrl);
        body2.put("clientId", config.getClientId());
        body2.put("identityId", userLoginResult.getIdentityId());
        HttpResponse httpResponse2 = null;

        log.info("我的请求参数 {}, {}", header2, body2);
        try {
            httpResponse2 = HttpUtils.doPost("https://appcuberun.cn-north-4.huaweicloud.com", authUrl, header2,
                    body2, JSONObject.toJSONString(body2));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(200 == httpResponse2.getStatusLine().getStatusCode()){
            String str = "";
            try {
                str = EntityUtils.toString(httpResponse2.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
            jsonObject = JSON.parseObject(str);
        }else{
            log.info("获取authcode失败。。。");
            for (Header allHeader : httpResponse2.getAllHeaders()) {
                log.info(allHeader.toString());
            }
            try {
                log.error("第三方接口获取异常 {}", EntityUtils.toString(httpResponse2.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    @Getter
    @Setter
    class UserLoginResult{

        private String identityId;

        private String loginAccessToken;

        public UserLoginResult(String identityId, String loginAccessToken){
            this.identityId = identityId;
            this.loginAccessToken = loginAccessToken;
        }
    }

    @Getter
    @Setter
    class HWResult{

        private Map<String, Object> result;

        private String resCode;

        private String resMsg;
    }
}
